package exercise;

import JZOffer.ListNode;

public class LC92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode tmpNode = new ListNode();
        tmpNode.next = head;
        ListNode cur1 = head;
        if (left == 1) {
            cur1 = tmpNode;
        } else {
            for (int i = 0; i < left - 2; i++) {
                cur1 = cur1.next;
            }
        }

        ListNode prev = cur1.next;
        ListNode cur = prev.next;


        for (int i = 0; i < right - left; i++) {
            ListNode curNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur = curNext;
        }

        cur1.next.next = cur;
        cur1.next = prev;

        return left == 1 ? cur1.next : head;
    }

    public static void main(String[] args) {
        LC92 lc92 = new LC92();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ListNode node = lc92.reverseBetween(head, 2, 4);
    }
}
